package com.zhengdongzulin.zuke.app.login

import android.app.Activity
import android.content.Intent
import android.text.TextUtils
import androidx.lifecycle.Observer
import com.google.gson.Gson
import com.lxj.androidktx.core.*
import com.zhengdongzulin.zuke.R
import com.zhengdongzulin.zuke.app.data.ChangeHomeData
import com.zhengdongzulin.zuke.app.main.ZKMainActivity
import com.zhengdongzulin.zuke.app.main.apartment.ZKHouseDetailsActivity
import com.zhengdongzulin.zuke.app.main.apartment.ZKStoreDetailsActivity
import com.zhengdongzulin.zuke.app.main.findhouse.ZKRoomDetailsActivity
import com.zhengdongzulin.zuke.app.main.mine.bill.ZKBillActivity
import com.zhengdongzulin.zuke.app.main.mine.collection.ZKCollectionFootprintActivity
import com.zhengdongzulin.zuke.app.main.mine.contract.ZKMyContractActivity
import com.zhengdongzulin.zuke.app.main.mine.doorlock.ZKDoorLockActivity
import com.zhengdongzulin.zuke.app.main.mine.waterAndElectricityMeter.ZKWAEMActivity
import com.zhengdongzulin.zuke.app.work.activity.ZKAddWorkActivity
import com.zhengdongzulin.zuke.app.work.activity.ZKWorkListActivity
import com.zhengdongzulin.zuke.base.BaseActivity
import com.zhengdongzulin.zuke.databinding.ActivityLoginBinding
import com.zhengdongzulin.zuke.ext.getTextZ
import com.zhengdongzulin.zuke.ext.put
import com.zhengdongzulin.zuke.ext.start
import rxhttp.wrapper.param.RxHttp

/**
 * jeff
 * 登录页面
 * 2021-06-01 17:36:48
 */
class LoginActivity : BaseActivity<LoginVm, ActivityLoginBinding>() {

    private var intentLaunchType: Int = 0
    private var tokenIntent: String? = ""

    override fun getLayoutResId(): Int = R.layout.activity_login

    override fun initVM(): LoginVm = getVM(LoginVm::class.java)

    override fun initView() {
        isInitDialog = true
    }

    override fun initData() {
    }

    override fun initListener() {
        mView.statusView.showLoading()
        tokenIntent = intent.getStringExtra("token")
        intentLaunchType = intent.getIntExtra("intentLaunchType", 0)

        mShareViewModel.token.value = tokenIntent
        RxHttp.setOnParamAssembly {
            if (!mShareViewModel.token.value.isNullOrEmpty()) {
                it.addHeader("Authorization", mShareViewModel.token.value)
            }
            it
        }
        //token模式
        mViewModel.web_account_get_list()
        //账号 模式
        //mViewModel.renter_user_login("13783576532", code = "100002")
    }

    override fun startObserve() {
        mViewModel.web_account_get_list.observe(this, androidx.lifecycle.Observer {
            var mData = it
            if (mData == null || mData?.size == 0) {
                toast("公寓类型初始化失败")
                finish()
                return@Observer
            }
            mShareViewModel.apartmentTypeId.value = mData!![0].id
            mShareViewModel.apartmentType.value = mData!![0].type
            sp().putString("apartmentTypeId", mData!![0].id)
            sp().putString("apartmentType", mData!![0].type)

            if (intentLaunchType == 0
                || intentLaunchType == 8
                || intentLaunchType == 9
                || intentLaunchType == 10
            ) {
                //这几种直接进到主界面
                goToNextActivity()
            } else {
                if (checkLogin()) {
                    mViewModel.renter_get_user_info(tokenIntent!!)
                }
            }
        })
        mViewModel.web_account_get_list.state.observe(
            this,
            getObserver(mViewModel.web_account_get_list)
        )

        mViewModel.renter_user_login.observe(this, Observer {
            sp().edit {
                putString("phone", mView.phone.getTextZ())
                putString("token", it.token)
                val toJson = it.toJson()
                putString("userInfo", toJson)
            }
            mShareViewModel.userInfo.value = it
            mShareViewModel.token.value = it.token

            RxHttp.setOnParamAssembly {
                if (!mShareViewModel.token.value.isNullOrEmpty()) {
                    it.addHeader("Authorization", mShareViewModel.token.value)
                }
                it
            }

            mViewModel.contract_list_house()

        })
        mViewModel.renter_user_login.state.observe(this, getObserver(mViewModel.renter_user_login))

        mViewModel.renter_get_user_info.observe(this, Observer {
            if ("1".equals(it.needLogin)) {
                needLogin()
                return@Observer
            }
            it?.let {
                sp().edit {
                    putString("phone", it.phone)
                    putString("token", tokenIntent)
                    val toJson = it.toJson()
                    putString("userInfo", toJson)
                }
                mShareViewModel.userInfo.value = it
                mShareViewModel.token.value = tokenIntent
                RxHttp.setOnParamAssembly {
                    if (!mShareViewModel.token.value.isNullOrEmpty()) {
                        it.addHeader("Authorization", tokenIntent)
                    }
                    it
                }
                mViewModel.contract_list_house()
            }
        })
        mViewModel.renter_get_user_info.state.observe(
            this,
            getObserver(mViewModel.renter_get_user_info)
        )

        mViewModel.contract_list_house.observe(this, Observer {
            if (it != null && it.size > 0) {
                var data = sp().getString("change_home", "")
                if (data.isNullOrEmpty()) {
                    sp().putString("change_home", it[0].toJson())
                }
            }
            goToNextActivity()
        })
        mViewModel.contract_list_house.state.observe(
            this,
            getObserver(mViewModel.contract_list_house)
        )
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == START_LOGIN_REQUEST && resultCode == Activity.RESULT_OK) {
            tokenIntent = mShareViewModel.token.value
            mViewModel.web_account_get_list()
        }
    }

    fun goToNextActivity() {

        when (intentLaunchType) {
            0 -> {
                Intent().start(this, ZKMainActivity::class.java)
            }
            1 -> {
                //1收藏
                Intent().put("type", "collection")
                    .start(this, ZKCollectionFootprintActivity::class.java)
            }
            2 -> {
                //2预约
                Intent().put("type", "reserve")
                    .start(this, ZKCollectionFootprintActivity::class.java)
            }
            3 -> {
                //3预定
                Intent().put("type", "reserve2")
                    .start(this, ZKCollectionFootprintActivity::class.java)
            }
            4 -> {
                // 4合同
                var data = sp().getString("change_home", "")
                if (data.isNullOrEmpty()) {
                    Intent().put("id", "")
                        .start(this, ZKMyContractActivity::class.java)
                } else {
                    Intent().put("id", Gson().fromJson(data, ChangeHomeData::class.java).houseId)
                        .start(this, ZKMyContractActivity::class.java)
                }
            }
            5 -> {
                //5账单
                Intent().start(this, ZKBillActivity::class.java)
            }
            6 -> {
                // 6智能锁、
                Intent().start(this, ZKDoorLockActivity::class.java)
            }
            7 -> {//7水电表
                Intent().start(this, ZKWAEMActivity::class.java)
            }
            8 -> {//8房间详情
                val houseId = intent.getStringExtra("houseId")
                if (TextUtils.isEmpty(houseId)) {
                    toast("请传递房间Id")
                    finish()
                } else {
                    houseId?.also {
                        Intent().put("id", it).start(this, ZKRoomDetailsActivity::class.java)
                    }
                }
            }
            9 -> {//9房型详情
                val roomId = intent.getStringExtra("roomId")
                if (TextUtils.isEmpty(roomId)) {
                    toast("请传递房型Id")
                    finish()
                } else {
                    roomId?.also {
                        Intent().put("id", it).start(this, ZKHouseDetailsActivity::class.java)
                    }
                }
            }
            10 -> {//10门店详情
                val storeId = intent.getStringExtra("storeId")
                if (TextUtils.isEmpty(storeId)) {
                    toast("请传递门店Id")
                    finish()
                } else {
                    storeId?.also {
                        Intent().put("id", it)
                            .start(this, ZKStoreDetailsActivity::class.java)
                    }
                }
            }
            11 -> {//11 报事报修
                Intent().put("type", "Baoshi").start(this, ZKAddWorkActivity::class.java)
            }
            12 -> {//12 服务申请
                Intent().put("type", "Baojie").start(this, ZKAddWorkActivity::class.java)
            }
            13 -> {//13 服务工单列表
                //服务申请列表传：服务申请，报事报修列表传：报事工单,维修工单（逗号隔开）
                Intent().put("incidentType", "服务申请").start(this, ZKWorkListActivity::class.java)
            }
            14 -> {//14 报修工单列表
                //服务申请列表传：服务申请，报事报修列表传：报事工单,维修工单（逗号隔开）
                Intent().put("incidentType", "报事工单,维修工单")
                    .start(this, ZKWorkListActivity::class.java)
            }
        }
        finish()
    }
}